package com.gengzp.system.controller;

import com.gengzp.common.constants.PermissionConstants;
import com.gengzp.common.document.annotations.Api;
import com.gengzp.common.document.annotations.ApiOperation;
import com.gengzp.common.model.base.req.SearchByIdReq;
import com.gengzp.common.model.base.resp.Result;
import com.gengzp.common.model.permission.req.AssignPermissionsToRoleReq;
import com.gengzp.common.model.permission.req.AssignRoleToUserReq;
import com.gengzp.common.model.permission.req.UnbindUserRoleRelationReq;
import com.gengzp.common.model.permission.resp.SearchPermissionResp;
import com.gengzp.common.model.permission.resp.SearchUserPermissionResp;
import com.gengzp.common.model.permission.resp.SearchUserRoleRelationResp;
import com.gengzp.common.utils.ExecutorUtils;
import com.gengzp.permission.annotation.CheckPermission;
import com.gengzp.permission.core.PermissionEnvironmentVariableReader;
import com.gengzp.system.service.IPermissionService;
import jakarta.validation.Valid;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

/**
 * @ClassName PermissionController
 * @Description 权限管理模块控制层
 * @Author gengzp
 * @Date 2025/5/16 21:38
 */
@RestController
@RequestMapping("/permission")
@Api(tags = "权限管理模块")
public class PermissionController {

    private static final Logger logger = LoggerFactory.getLogger(PermissionController.class);

    @Autowired
    private IPermissionService permissionService;

    /**
     * 查询系统所有权限
     */
    @PostMapping("/search")
    @ApiOperation(value = "查询系统所有权限")
    @CheckPermission(PermissionConstants.PERMISSION_READ)
    public Result<SearchPermissionResp> searchPermission() {
        return Result.getSuccessResult(permissionService.searchPermission());
    }

    /**
     * 为用户分配角色
     */
    @PostMapping("/assign_roles_to_user")
    @ApiOperation(value = "为用户分配角色")
    @CheckPermission(PermissionConstants.PERMISSION_WRITE)
    public Result<Void> assignRoles2User(@Valid @RequestBody AssignRoleToUserReq req) {
        permissionService.assignRoles2User(req);
        return Result.getSuccessResult();
    }

    /**
     * 为角色分配权限
     */
    @PostMapping("/assign_permissions_to_role")
    @ApiOperation(value = "为角色分配权限")
    @CheckPermission(PermissionConstants.PERMISSION_WRITE)
    public Result<Void> assignPermissions2Role(@Valid @RequestBody AssignPermissionsToRoleReq req) {
        permissionService.assignPermissions2Role(req);
        return Result.getSuccessResult();
    }

    /**
     * 查询用户角色的关联关系
     */
    @PostMapping("/search_user_role_relation")
    @ApiOperation(value = "查询用户角色的关联关系")
    @CheckPermission(PermissionConstants.PERMISSION_READ)
    public Result<SearchUserRoleRelationResp> searchUserRoleRelation(@Valid @RequestBody SearchByIdReq req) {
        return Result.getSuccessResult(permissionService.searchUserRoleRelation(Long.valueOf(req.getId())));
    }

    /**
     * 根据用户id查询拥有的权限
     */
    @PostMapping("/search_permission_by_userId")
    @ApiOperation(value = "根据用户id查询拥有的权限")
    @CheckPermission(PermissionConstants.PERMISSION_READ)
    public Result<SearchUserPermissionResp> searchPermissionByUserId(@Valid @RequestBody SearchByIdReq req) {
        return Result.getSuccessResult(permissionService.searchPermissionByUserId(Long.valueOf(req.getId())));
    }

    /**
     * 解绑用户和角色
     */
    @PostMapping("/unbind_user_role_relation")
    @ApiOperation(value = "解绑用户和角色")
    @CheckPermission(PermissionConstants.PERMISSION_WRITE)
    public Result<Void> unbindUserRoleRelation(@Valid @RequestBody UnbindUserRoleRelationReq req) {
        permissionService.unbindUserRoleRelation(Long.valueOf(req.getUserId()), Long.valueOf(req.getRoleId()));
        return Result.getSuccessResult();
    }

    /**
     * 刷新缓存中的角色权限
     */
    @PostMapping("/refresh_cache_permission")
    @ApiOperation(value = "刷新缓存中的角色权限")
    @CheckPermission(PermissionConstants.PERMISSION_WRITE)
    public Result<Void> refreshCachePermissions() {
        ExecutorUtils.getThreadPool().execute(() -> {
                    logger.info("开始刷新角色权限缓存数据");
                    try {
                        permissionService.refreshCachePermissions();
                        logger.info("刷新角色权限缓存数据成功");
                    } catch (Exception e) {
                        logger.info("刷新角色权限缓存数据失败: " + e.getMessage());
                    }
                }
        );
        return Result.getSuccessResult();
    }

}
